﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc;

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

using ProjectBase.Core;
using ProjectBase.Core.Binding;

namespace $safeprojectname$.Import.Excel
{
    public class ExcelValueProvider : MvcValueContainer
    {
        public ExcelValueProvider(IValueProvider valueProvider) : base (valueProvider) {}

        public static ExcelValueProvider Create(Row propertyKeys, Row data, SharedStringTable sharedStringTable, out bool isNotEmpty)
        {
            Contract.Requires(propertyKeys.Is());
            Contract.Requires(data.Is());

            isNotEmpty = false;
            var nameValues = new NameValueCollection();

            foreach (var headerCell in propertyKeys.Descendants<Cell>())
            {
                var key = headerCell.GetValue(sharedStringTable);

                var cell = data.Descendants<Cell>()
                    .FirstOrDefault(c => c.GetColumnName().Equals(headerCell.GetColumnName()));

                var attemptedValue = cell.Is()
                    ? cell.GetValue(sharedStringTable)
                    : string.Empty;

                isNotEmpty |= attemptedValue.IsNotEmpty();

                nameValues.Add(key, attemptedValue);
            }
            var provider = new NameValueCollectionValueProvider(nameValues, CultureInfo.InvariantCulture);
            return new ExcelValueProvider(provider);
        }
    }
}
